<!-- Create events calendar -->
<?php
  use_helper('Calendar');

  // Initialize usefull variables
  $initial_time = strtotime($year.'-'.$month.'-01');
  $last_month_day = date('t', $initial_time);

  // Initialize calendar days
  $days = array();
  for($i=1; $i<=$last_month_day; $i++)
  {
    $days[$i] = array(
      CALENDAR_DAY_LINK_FIELD => NULL,
      CALENDAR_DAY_CLASS_FIELD => 'empty_day',
      CALENDAR_DAY_CONTENT_FIELD => NULL
    );
  }

  // Add events to calendar
  foreach ($month_events as $event)
  {
    if ($event->getStartDate('m') < $month)
      $start_day = '01';
    else
      $start_day = $event->getStartDate('d');
    if ($event->hasEndDate())
    {
      $end_day = $event->getEndDate('d');
      if ($end_day < $start_day)
        $end_day = $event->getStartDate('t');
    }
    else
      $end_day = $start_day;

    for($day=$start_day; $day<=$end_day; $day++)
    {
      if ($days[intval($day)][CALENDAR_DAY_LINK_FIELD] == NULL)
      {
        $days[intval($day)][CALENDAR_DAY_LINK_FIELD] = url_for('event/index?day='.sprintf('%02d',$day).'&month='.sprintf('%02d',$month).'&year='.$year);
        $days[intval($day)][CALENDAR_DAY_CLASS_FIELD] = 'event_day';
      }
    }
  }

  // Create month before link
  $bMonthURL = url_for('event/index?month='.date('m',$initial_time-1).'&year='.date('Y',$initial_time-1));

  // Create month after link
  $aMonthTime = $initial_time + ($last_month_day*24*60*60) + 1;
  $aMonthURL = url_for('event/index?month='.date('m',$aMonthTime).'&year='.date('Y',$aMonthTime));

  // Generate calendar
  $pn = array('&laquo;'=>$bMonthURL, '&raquo;'=>$aMonthURL);
  setlocale(LC_TIME, 'pt_BR');
  echo generate_calendar($year, $month, $days, 3, url_for('event/index?month='.$month.'&year='.$year), 0, $pn); 
?>
